package netty.io.demo.Netty.echo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class NettyServer {
  private final int port;
  
  NettyServer(int port) {
    this.port = port;
  }
  
  public void start() throws InterruptedException {
    // 线程组
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    
    try {
      // server 启动器
      ServerBootstrap b = new ServerBootstrap();
      b.group(group)
          // 实现 通道的方式
          .channel(NioServerSocketChannel.class)
          // 作为 服务端 绑定的地址
          .localAddress(new InetSocketAddress(this.port))
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
              // 通过 pipeline 添加 handle
              socketChannel.pipeline().addLast(new ServerHandler());
            }
          });
      
      // 表示 同步绑定
      ChannelFuture cf = b.bind().sync();
      // 阻塞 直到服务器 channel 关闭
      cf.channel().closeFuture().sync();
    } finally {
      // 这里针对 线程组 进行优雅降级
      group.shutdownGracefully().sync();
    }
  }
  
  public static void main(String[] args) throws InterruptedException {
    System.out.println("服务开始 ...");
    new NettyServer(10020).start();
    System.out.println("服务结束 ...");
  }
}
